package lib.bone.audit.workload.listener;

import cn.hutool.core.io.FileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lib.bone.audit.workload.domain.NepuWorkload;
import lib.bone.access.constant.WorkloadSourceConst;
import lib.bone.access.constant.WorkloadTypeConst;
import lib.bone.audit.workload.domain.dto.TeachingWorkloadImportDTO;
import lib.bone.audit.workload.service.NepuWorkloadService;
import lib.bone.common.utils.JsonUtil;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.module.iojob.constant.JobStatusConst;
import lib.bone.system.module.iojob.domain.IOJob;
import lib.bone.system.module.iojob.domain.IOLog;
import lib.bone.system.module.iojob.service.IOJobService;
import lib.bone.system.service.SysDeptService;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
public class TeachingWorkloadListener extends AnalysisEventListener<TeachingWorkloadImportDTO> {

    /**
     * 文件父路径
     */
    String fileParentPath;
    /**
     * 周期ID
     */
    String cycleId;
    /**
     * 父周期ID
     */
    String parentCycleId;
    /**
     * 任务ID
     */
    String ioJobId;
    /**
     * 用户服务
     */
    SysUserService userService;
    /**
     * 工作量服务
     */
    NepuWorkloadService workloadService;
    /**
     * 部门服务
     */
    SysDeptService deptService;
    /**
     * 导入导出服务
     */
    IOJobService ioJobService;
    /**
     * 操作日志
     */
    List<IOLog> logs = new ArrayList<>();

    public TeachingWorkloadListener(SysUserService userService, SysDeptService deptService, NepuWorkloadService workloadService, IOJobService ioJobService,String cycleId, String ioJobId,String fileParentPath){
        this.userService = userService;
        this.deptService = deptService;
        this.workloadService = workloadService;
        this.ioJobService = ioJobService;
        this.cycleId = cycleId;
        this.ioJobId = ioJobId;
        this.fileParentPath = fileParentPath;
    }

    public TeachingWorkloadListener(SysUserService userService, SysDeptService deptService, NepuWorkloadService workloadService, IOJobService ioJobService,String cycleId,String parentCycleId, String ioJobId,String fileParentPath){
        this.userService = userService;
        this.deptService = deptService;
        this.workloadService = workloadService;
        this.ioJobService = ioJobService;
        this.cycleId = cycleId;
        this.parentCycleId = parentCycleId;
        this.ioJobId = ioJobId;
        this.fileParentPath = fileParentPath;
    }


    @Override
    public void invoke(TeachingWorkloadImportDTO teachingWorkloadImportDTO, AnalysisContext analysisContext) {
        // 工作量记录新增 userName;
        Optional<SysUser> userOp = userService.findByUserName(teachingWorkloadImportDTO.getUserName());
        if (!userOp.isPresent()) {
            log.info("{}对应用户信息不存在", teachingWorkloadImportDTO.getUserName());
            return;
        }
        SysUser user = userOp.get();
        Long userId = user.getId();
        // 查询工作量记录是否存在
        NepuWorkload workload = new NepuWorkload();
        workload.setCycleId(cycleId);
        workload.setParentId(parentCycleId);
        workload.setUserId(userId);
        workload.setWorkloadType(WorkloadTypeConst.TEACH);
        Example<NepuWorkload> example = Example.of(workload);
        List<NepuWorkload> queryList = workloadService.getExampleWorkloads(example);
        if (queryList.size() >= 1){
            IOLog ioLog = new IOLog();
            ioLog.setId((long) (logs.size()+1));
            ioLog.setErrMsg("已存在的教学工作量记录");
            ioLog.setParams(JsonUtil.obj2String(teachingWorkloadImportDTO));
            logs.add(ioLog);
            log.info("{},{}该周期已存在教学工作量记录",teachingWorkloadImportDTO.getUserName(),teachingWorkloadImportDTO.getNickName());
        }else {
            workload.setWorkload(teachingWorkloadImportDTO.getWorkload());
            workload.setUsedWorkload(0.0);
            workload.setUsedUp(0);
            workload.setWorkloadLock(1);
            workload.setWorkloadSource(WorkloadSourceConst.MANAGER);
            workload.setWorkloadAttach(null);
            workloadService.saveOne(workload);
            log.info("{},{}写入成功教学工作量{}",teachingWorkloadImportDTO.getUserName(),teachingWorkloadImportDTO.getNickName(),teachingWorkloadImportDTO.getWorkload());
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        Optional<IOJob> ioJobOp = ioJobService.getById(ioJobId);
        if (!ioJobOp.isPresent()) {
            log.error("导入任务丢失");
            return;
        }
        IOJob ioJob = ioJobOp.get();
        String filePath = fileParentPath+ File.separator+ioJob.getId()+File.separator+"log.xlsx";
        FileUtil.touch(filePath);
        EasyExcel.write(filePath,IOLog.class).sheet("sheet").doWrite(logs);

        ioJob.setJobStatus(JobStatusConst.FINISHED);
        ioJob.setLogFilePath(filePath);
        ioJobService.updateOne(ioJob);
        log.info("教学工作量导入完成");
    }
}
